package com.aizuda.easyManagerTool.service.server.impl;

import cn.hutool.core.util.StrUtil;
import com.aizuda.easy.security.domain.Rep;
import com.aizuda.easy.security.domain.Req;
import com.aizuda.easyManagerTool.domian.dto.server.ServerSettingDTO;
import com.aizuda.easyManagerTool.domian.vo.setting.SettingUserVO;
import com.aizuda.easyManagerTool.service.server.ServerSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class ServerSettingStrategy {

    private Map<String, ServerSettingService> gtServiceMap = new ConcurrentHashMap<>();

    @Autowired
    public ServerSettingStrategy(Map<String, ServerSettingService> gtServiceMap) {
        this.gtServiceMap = gtServiceMap;
    }

    public List get(String str){
        Rep<List> rep = gtServiceMap.get(str).find(null);
        return rep.getData();
    }

    public Rep del(Req<ServerSettingDTO, SettingUserVO> req){
        ServerSettingDTO data = req.getData();
        return gtServiceMap.get(data.getKey()).del(req);
    }

    public Rep edit(Req<ServerSettingDTO, SettingUserVO> req){
        ServerSettingDTO data = req.getData();
        return gtServiceMap.get(data.getKey()).edit(req);
    }

    public Map<String,List> getAll(String str){
        Map<String, List> all = getOnDemand();
        if(StrUtil.isEmpty(str)){
            return all;
        }
        List<String> strings = Arrays.asList(str.split(","));
        Iterator<String> iterator = all.keySet().stream().iterator();
        while (iterator.hasNext()){
            String next = iterator.next();
            if(strings.contains(next)){
                continue;
            }
            all.remove(next);
        }
        return all;
    }

    private Map<String,List> getOnDemand(){
        Map<String,List> map = new ConcurrentHashMap<>(gtServiceMap.size());
        gtServiceMap.keySet().stream().forEach(item -> {
            Rep<List> rep = gtServiceMap.get(item).find(null);
            map.put(item,rep.getData());
        });
        return map;
    }

}
